package cn.joyfulmedia.common.dto;

import cn.joyfulmedia.common.log.AppKeyHelper;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

import static com.google.common.base.Preconditions.checkArgument;
import static org.apache.commons.lang3.StringUtils.*;

/**
 * 公用请求头参数
 *
 * @author yujun
 * @create 2017-04-06 10:11
 */
public class BaseRequestHeader implements Serializable {

    private String uid;         //	登录态必传	-	用户ID	135005fc87fdc1518607946d68b320ee
    private String token;       //	登录态必传	-	用户token	X98911TVMWWBWPGP8381
    private String appVersion;  //	必传	-	客户端版本号	3.0.2
    private String osVersion;   //	必传	-	系统版本	10.2
    private String device;      //	APP必传	-	设备型号	iPhone_6s_Plus
    private String deviceId;    //	APP必传	-	设备ID	F051D27D-5474-41F2-B34E-8607C13CEFE4
    private String appKey;      //	必传	-	直播分配	找直播后台研发人员申请,见 com.imgo.max.common.log.AppKeyHelper
    private String uip;         //  后台从request中获取  -  用户IP
    private String companyId;         //  后台从request中获取  -  用户IP

    /**
     * 从request中获取header参数
     * 兼容老版本从param中取部分参数
     *
     * @param request request
     * @return BaseRequestHeader
     */
    public static BaseRequestHeader build(HttpServletRequest request) {
        BaseRequestHeader header = new BaseRequestHeader();
        header.setUid(request.getHeader("uid") == null ? request.getParameter("uid") : request.getHeader("uid"));
        header.setToken(request.getHeader("token") == null ? request.getParameter("token") : request.getHeader("token"));
        header.setAppVersion(request.getHeader("appVersion") == null ? request.getParameter("appVersion") : request.getHeader("appVersion"));
        header.setOsVersion(request.getHeader("osVersion") == null ? request.getParameter("osVersion") : request.getHeader("osVersion"));
        header.setDevice(request.getHeader("device") == null ? request.getParameter("device") : request.getHeader("device"));
        header.setDeviceId(request.getHeader("deviceId") == null ? request.getParameter("deviceId") : request.getHeader("deviceId"));
        header.setUip(getIpAddress(request));
        return header;
    }

    /**
     * 获取用户ip
     *
     * @param request request
     * @return string
     */
    public static String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if (isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = "0.0.0.0";
        }
        return ip;
    }

    /**
     * 获取本机地址
     *
     * @return string
     */
    public static String getLocalIpAddress() throws SocketException {
        Enumeration allNetInterfaces = NetworkInterface.getNetworkInterfaces();
        InetAddress ip;
        while (allNetInterfaces.hasMoreElements()) {
            NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
            Enumeration addresses = netInterface.getInetAddresses();
            while (addresses.hasMoreElements()) {
                ip = (InetAddress) addresses.nextElement();
                if (ip != null && ip instanceof Inet4Address) {
                    // System.out.println(JSON.toJSONString(ip));
                    return ip.getHostAddress();
                }
            }
        }
        return "0.0.0.0";
    }

    /**
     * 验证head参数
     */
    public static void verifyRequestHeader(BaseRequestHeader header) {
//        checkArgument(isNotBlank(header.getAppVersion()), "appVersion不正确");
//        checkArgument(isNotBlank(header.getOsVersion()), "osVersion不正确");
//        AppKeyHelper.AppKey key = systemSource(header.getAppKey());
//        if (key.source.equals("android") || key.source.equals("ios")) {
//            checkArgument(isNotBlank(header.getDevice()), "device不正确");
//            checkArgument(isNotBlank(header.getDeviceId()), "deviceId不正确");
//        }
    }

    /**
     * 验证登录状态下的head参数
     */
    public static void verifyRequestHeaderByLogin(BaseRequestHeader header) {
        checkArgument(isNotBlank(header.getUid()) && header.getUid().length() == 32, "uid不正确");
        checkArgument(isNotBlank(header.getToken()), "token不正确");
        verifyRequestHeader(header);
    }

    /**
     * 是否IOS端
     *
     * @return boolean
     */
    public static boolean isIOS(String appKey) {
        checkArgument(isNotBlank(appKey) && appKey.length() == 10, "appKey不正确");
        return systemSource(appKey).source.equals("ios");
    }

    /**
     * 是否android端
     *
     * @return boolean
     */
    public static boolean isAndroid(String appKey) {
        checkArgument(isNotBlank(appKey) && appKey.length() == 10, "appKey不正确");
        return systemSource(appKey).source.equals("android");
    }

    /**
     * 是否h5
     *
     * @param appKey appKey
     * @return boolean
     */
    public static boolean isH5(String appKey) {
        checkArgument(isNotBlank(appKey) && appKey.length() == 10, "appKey不正确");
        return systemSource(appKey).source.equals("h5");
    }

    public static boolean isPC(String appKey) {
        checkArgument(isNotBlank(appKey) && appKey.length() == 10, "appKey不正确");
        return systemSource(appKey).source.equals("pc");
    }

    /**
     * 获取版本int值，用于进行特殊版本处理
     *
     * @param header
     * @return
     */
    public static int getAppIntVersion(BaseRequestHeader header) {
        if (isNotBlank(header.getAppVersion())) {
            String av = header.getAppVersion().replaceAll("\\.", "");
            if (isNumeric(av)) {
                return Integer.parseInt(av);
            } else
                return 0;
        } else
            return 0;
    }

    /**
     * 解析appKey
     *
     * @param appKey appKey
     * @return
     */
    public static AppKeyHelper.AppKey systemSource(String appKey) {
        return AppKeyHelper.getSourceType(appKey);
    }

    /**
     * 获取app终端信息
     *
     * @param appKey appKey
     * @return
     */
    public static String getEndType(String appKey) {
        return systemSource(appKey).source;
    }

    /**
     * 获取app平台信息
     *
     * @param appKey appKey
     * @return
     */
    public static String getPlatfom(String appKey) {
        return AppKeyHelper.getSourceType(appKey).platform;
    }

    public String getCompanyId() {
        return companyId;
    }

    public void setCompanyId(String companyId) {
        this.companyId = companyId;
    }

    public String getUid() {
        return uid;
    }

    public void setUid(String uid) {
        this.uid = uid;
    }

    public String getToken() {
        return token;
    }

    public void setToken(String token) {
        this.token = token;
    }

    public String getAppVersion() {
        return appVersion;
    }

    public void setAppVersion(String appVersion) {
        this.appVersion = appVersion;
    }

    public String getOsVersion() {
        return osVersion;
    }

    public void setOsVersion(String osVersion) {
        this.osVersion = osVersion;
    }

    public String getDevice() {
        return device;
    }

    public void setDevice(String device) {
        this.device = device;
    }

    public String getUip() {
        return uip;
    }

    public void setUip(String uip) {
        this.uip = uip;
    }

    public String getDeviceId() {
        return deviceId;
    }

    public void setDeviceId(String deviceId) {
        this.deviceId = deviceId;
    }

    public String getAppKey() {
        return appKey;
    }

    public void setAppKey(String appKey) {
        this.appKey = appKey;
    }

}
